<template>
  <div class="register-container" @click="showDisclaimerDialog">
    <div class="register-box" @click.stop>
      <div class="welcome-area">
        <img src="../assets/svg/vite.svg" alt="Logo" class="logo float-animation">
        <h1 class="gradient-text">欢迎加入</h1>
        <p>注册账号，开启您的全新体验</p>
      </div>
      <div class="register-form-container">
        <div class="register-form">
          <div class="form-header">
            <h2>用户注册</h2>
            <el-button link icon="ArrowLeft" @click="goBack">返回</el-button>
          </div>
          <el-form :model="registerForm" :rules="rules" ref="registerFormRef" label-width="0" @keyup.enter="handleEnterSubmit" @submit.prevent>
            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
                prefix-icon="User"
                maxlength="20"
                @compositionstart="inputComposing = true"
                @compositionend="inputComposing = false"
              ></el-input>
            </el-form-item>
            <el-form-item prop="phone">
              <el-input
                v-model="registerForm.phone"
                placeholder="请输入手机号"
                prefix-icon="Iphone"
                maxlength="11"
                @compositionstart="inputComposing = true"
                @compositionend="inputComposing = false"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="Lock"
                show-password
                @compositionstart="inputComposing = true"
                @compositionend="inputComposing = false"
              ></el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请确认密码"
                prefix-icon="Lock"
                show-password
                @compositionstart="inputComposing = true"
                @compositionend="inputComposing = false"
              ></el-input>
            </el-form-item>
            <el-form-item prop="code">
              <div class="captcha-container">
                <el-input
                  v-model="registerForm.code"
                  placeholder="请输入验证码"
                  prefix-icon="Key"
                  @compositionstart="inputComposing = true"
                  @compositionend="inputComposing = false"
                ></el-input>
                <div class="captcha-wrapper">
                  <div v-if="captchaLoading" class="captcha-loading">
                    <el-icon class="loading-icon"><Loading /></el-icon>
                  </div>
                  <img
                    v-else
                    :src="captchaUrl"
                    alt="验证码"
                    class="captcha-img"
                    @click="refreshCaptcha"
                    v-show="captchaUrl"
                  />
                </div>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                class="register-button"
                :loading="loading"
                @click="handleRegister"
              >
                注册
              </el-button>
            </el-form-item>
            <div class="login-link">
              已有账号？<a href="javascript:;" @click="handleLogin">立即登录</a>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Loading } from '@element-plus/icons-vue';
import {captchaIdAPI, captchaImageAPI, registerAPI} from '../api/auth';
import { 
  showSuccess, 
  showWarning, 
  showError, 
  showDisclaimer 
} from '../components/layout/GlobalNotification.vue';

const router = useRouter();
const loading = ref(false);
const captchaUrl = ref('');
const captchaId = ref(''); // 存储验证码ID
const registerFormRef = ref();
const captchaLoading = ref(true); // 验证码加载状态
const inputComposing = ref(false); // 是否正在输入中文

// 表单数据
const registerForm = reactive({
  phone: '',
  username: '',
  password: '',
  confirmPassword: '',
  captchaId: '', // 存储验证码ID
  code: ''
});

// 验证规则
const validatePhone = (rule, value, callback) => {
  const phoneRegex = /^1[3-9]\d{9}$/; // 国内手机号验证规则
  if (!value) {
    callback(new Error('请输入手机号'));
  } else if (!phoneRegex.test(value)) {
    callback(new Error('请输入正确的手机号格式'));
  } else {
    callback();
  }
};

const validateUsername = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入用户名'));
  } else if (value.length < 3 || value.length > 20) {
    callback(new Error('用户名长度应在3-20个字符之间'));
  } else {
    callback();
  }
};

const validatePassword = (rule, value, callback) => {
  // 密码强度规则：6-15位，必须包含数字和字母，必须包含特殊字符(@、#、_、~)
  const passwordRegex = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[@#_~])[\w@#_~]{6,15}$/;
  if (!value) {
    callback(new Error('请输入密码'));
  } else if (!passwordRegex.test(value)) {
    callback(new Error('密码格式不符合要求，请包含数字、字母和特殊字符(@#_~)'));
  } else {
    callback();
  }
};

const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请确认密码'));
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { validator: validateUsername, trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
};

// 获取验证码（完整流程）
const getCaptcha = async () => {
  try {
    captchaLoading.value = true;
    captchaUrl.value = '';

    const id = await captchaIdAPI();
    if (!id) throw new Error('无法获取验证码ID');

    captchaId.value = id;
    registerForm.captchaId = id;

    // Load image with cleaner syntax
    await new Promise((resolve, reject) => {
      const img = new Image();
      img.onload = resolve;
      img.onerror = () => reject(new Error('验证码图片加载失败'));
      img.src = captchaImageAPI(id);
    });

    captchaUrl.value = captchaImageAPI(id);

  } catch (error) {
    showError(error.message || '验证码加载失败，请点击刷新');
  } finally {
    captchaLoading.value = false;
  }
};

// 刷新验证码
const refreshCaptcha = async () => {
  registerForm.code = '';
  await getCaptcha();
  showSuccess('验证码已刷新', 1500);
};

// 处理回车键提交
const handleEnterSubmit = (event) => {
  // 如果是正在输入中文，不提交表单
  if (inputComposing.value) {
    event.preventDefault();
    return;
  }
  
  // 按下回车键提交表单
  if (event.key === 'Enter') {
    handleRegister();
  }
};

// 提交注册表单
const handleRegister = async () => {
  // 先判断是否正在输入中文
  if (inputComposing.value) {
    return;
  }
  
  // 检查所有输入是否完整
  if (!registerForm.username || !registerForm.phone || !registerForm.password || !registerForm.confirmPassword || !registerForm.code) {
    showWarning('请填写完整的注册信息');
    return;
  }
  
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      
      try {
        // 调用注册接口
        const res = await registerAPI(registerForm);
        
        if (res && res.code === 200) {
          // 注册成功
          showSuccess(res.msg || '注册成功');
          
          // 延迟1.5秒后跳转到登录页
          setTimeout(() => {
            router.push('/login');
          }, 1500);
        } else {
          // 注册失败
          showError(res.msg || '注册失败，请检查填写的信息');
          // 刷新验证码
          await refreshCaptcha();
        }
      } catch (error) {
        console.error('注册错误:', error);
        showError('注册请求出错，请重试');
        // 刷新验证码
        await refreshCaptcha();
      } finally {
        loading.value = false;
      }
    } else {
      showWarning('请按要求填写注册信息');
    }
  });
};

// 返回上一页
const goBack = () => {
  router.push('/');
};

// 显示免责声明对话框
const showDisclaimerDialog = () => {
  showDisclaimer();
};

// 跳转到登录页
const handleLogin = () => {
  router.push('/login');
};

// 组件挂载时获取验证码
onMounted(async () => {
  await getCaptcha();
});
</script>

<style scoped>
.register-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('../assets/images/xiaomi2.png');
  background-size: cover;
  background-position: center;
  position: relative;
  cursor: pointer;
}

.register-box {
  display: flex;
  width: 900px;
  height: 600px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  cursor: default;
  position: relative;
  z-index: 10;
}

.welcome-area {
  flex: 1.8;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, var(--el-color-primary) 0%, #67c23a 100%);
  color: white;
  padding: 40px;
  text-align: center;
}

.welcome-area h1 {
  font-size: 32px;
  margin: 20px 0;
  font-weight: 600;
}

.welcome-area p {
  font-size: 16px;
  opacity: 0.9;
  line-height: 1.6;
}

.logo {
  width: 120px;
  height: 120px;
  margin-bottom: 20px;
}

.register-form-container {
  flex: 3;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30px;
}

.register-form {
  width: 100%;
  max-width: 400px;
}

.captcha-container {
  display: flex;
  gap: 30px;
  align-items: center;
}

.captcha-container .el-input {
  flex: 1;
  min-width: 0;
  width: calc(100% + 10px);
}

.captcha-wrapper {
  position: relative;
  width: 140px;
  height: 45px;
  flex-shrink: 0;
  border-radius: 4px;
  overflow: hidden;
  background-color: #f8f8f8;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.captcha-img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: opacity 0.3s;
}

.captcha-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f8f8f8;
}

.loading-icon {
  font-size: 24px;
  color: var(--el-color-primary);
  animation: rotate 1.5s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.register-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 8px;
  background: linear-gradient(90deg, var(--el-color-primary), #67c23a);
  border: none;
}

.register-button:hover {
  background: linear-gradient(90deg, #66b1ff, #85ce61);
}

.login-link {
  text-align: center;
  margin-top: 16px;
  font-size: 14px;
  color: #666;
}

.login-link a {
  color: var(--el-color-primary);
  text-decoration: none;
  font-weight: 600;
}

.login-link a:hover {
  text-decoration: underline;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.form-header h2 {
  margin: 0;
  text-align: left;
  font-size: 28px;
  color: #333;
}

.gradient-text {
  background: linear-gradient(90deg, #ffffff, #f0f0f0);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.float-animation {
  animation: float 6s ease-in-out infinite;
}

@keyframes float {
  0% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
  100% { transform: translateY(0px); }
}

:deep(.el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
}

:deep(.el-input__inner) {
  height: 44px;
}

:deep(.el-button) {
  font-weight: 600;
}

:deep(.el-checkbox__label) {
  font-size: 14px;
  color: #666;
}

:deep(.disclaimer-content) {
  line-height: 1.8;
  color: #606266;
  text-align: left;
}

:deep(.disclaimer-content p) {
  margin-bottom: 10px;
}
</style>